package cn.login;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import cn.dbconnection.DBConnection;
import cn.dbconnection.MD5Crypt;

public class Login {

	private static String sql = "SELECT pass FROM daim_member WHERE userName = ?";
	private Connection conn = null;
	private PreparedStatement pstmt = null;
	private ResultSet rs = null;

	public Login() {
		conn = DBConnection.getConnection();
	}

	public int login(String userName, String password) {
		String db_pass = null;
		String pass = null;
		if (userName != null && password != null) {
			try {
				pstmt = conn.prepareStatement(sql);
				pstmt.setString(1, userName);
				pstmt.executeQuery();
				rs = pstmt.getResultSet();
				if (rs.next()) {
					db_pass = rs.getString("pass").trim();
					pass = MD5Crypt.crypt(password, db_pass.substring(3, 5));
					if (pass.equals(db_pass)) {
						return 1;
					}
				}
			} catch (SQLException sqle) {
				sqle.printStackTrace();
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} finally {
				try {
					if (rs != null) {
						rs.close();
					}
					if (pstmt != null) {
						pstmt.close();
					}
					if (conn != null) {
						conn.close();
					}
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}
		return 2;
	}
}
